package org.xhnews.bo;

import java.util.Vector;

import org.xhnews.database.DatabaseManager;
import org.xhnews.download.DownloadManager;
import org.xhnews.preferences.Preferences;
import org.xhnews.to.RssChannel;
import org.xhnews.to.RssItem;
import org.xhnews.utils.StringUtil;

public class RssBo {
	/*
	 * 获得所有RSS频道
	 */
	public static Vector getAllRssChannels() {
		return DatabaseManager.getAllRssChannels();
	}
    /*
     * 根据RSS频道ID获取所有RSS条目
     */
	public static Vector getRssByChannel(String channelId) {
		return DatabaseManager.getRssByChannel(channelId);
	}
    /*
     * 设置RSS条目为已读状态
     */
	public static void setRssItemRead(String id) {
		DatabaseManager.setRssItemRead(id, true);
	}
    /*
     * 根据RSS条目ID获得RSS条目
     */
	public static RssItem getRssItemByID(String ID) {
		return DatabaseManager.getRssItemByID(ID);
	}
    /*
     * 添加RSS频道
     */
	public static String appendRssChannel(RssChannel ch) {
		return DatabaseManager.appendRssChannel(ch);
	}
    /*
     * 更改RSS频道
     */
	public static void updateRssChannel(RssChannel ch) {
		DatabaseManager.updateRssChannel(ch);
	}
    /*
     * 根据ID删除RSS条目
     */
	public static void delRssChannelById(String id) {
		DatabaseManager.delRssChannelById(id);
	}
   /*
    * 根据频道获得该频道最新的RSS条目
    */
	public static Vector getNewRSSOfChannel(RssChannel rssChannel) {
		Vector items = DownloadManager.downloadRSSOfChannel(rssChannel);
		DatabaseManager.insertRssItems(items, rssChannel.getId(),
				Preferences.news_max_count_per_channel);
		return items;
	}
    public static String maikeUrl(String contain, String notContain, int searchregion) {
		return "http://news.baidu.com/ns?"
				+ makeKey(StringUtil.urlEncode(contain), StringUtil.urlEncode(notContain),
						searchregion)
				+ "&tn=newsrss&sr=1&cl=2&rn=30&ct=100&clk=sortbytime&ie=utf-8";
	}

	private static String makeKey(String contain, String notContain, int searchregion) {
		String key = "";

		if (!contain.equals("") && contain != null) {
			key += "q1=" + contain;
		}
		if (!notContain.equals("") && notContain != null) {
			key += "&q4=" + notContain;
		}

		if (searchregion == 0)// 0:title 1:text
			key += "&q5=1";
		return key;
	}
	public static RssChannel makeRssChannelObject(String name,String keycontain, String keynotcontain, int searchregion){
		RssChannel rsschannel=new RssChannel();
		rsschannel.setName(name);
		rsschannel.setKeycontain(keycontain);
		rsschannel.setKeynotcontain(keynotcontain);
		rsschannel.setSearchregion(searchregion);
		rsschannel.setLink(maikeUrl(keycontain,keynotcontain,searchregion));
		return rsschannel;
	}
}
